package com.it.smartoldb.controller;

import com.it.smartoldb.common.Result;
import com.it.smartoldb.entity.Appointment;
import com.it.smartoldb.service.AppointmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 预约管理控制器
 */
@RestController
@RequestMapping("/api/appointments")
public class AppointmentController {

    @Autowired
    private AppointmentService appointmentService;

    /**
     * 创建预约
     */
    @PostMapping
    public Result<Appointment> createAppointment(@RequestBody Appointment appointment) {
        try {
            Appointment created = appointmentService.createAppointment(appointment);
            return Result.success(created);
        } catch (RuntimeException e) {
            return Result.error(400, e.getMessage());
        }
    }

    /**
     * 更新预约
     */
    @PutMapping("/{id}")
    public Result<Appointment> updateAppointment(@PathVariable Long id, 
                                               @RequestBody Appointment appointment) {
        try {
            Appointment updated = appointmentService.updateAppointment(id, appointment);
            return Result.success(updated);
        } catch (RuntimeException e) {
            return Result.error(400, e.getMessage());
        }
    }

    /**
     * 删除预约
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteAppointment(@PathVariable Long id) {
        try {
            appointmentService.deleteAppointment(id);
            return Result.success(null);
        } catch (RuntimeException e) {
            return Result.error(400, e.getMessage());
        }
    }

    /**
     * 根据ID查找预约
     */
    @GetMapping("/{id}")
    public Result<Appointment> getAppointmentById(@PathVariable Long id) {
        Optional<Appointment> appointment = appointmentService.findById(id);
        if (appointment.isPresent()) {
            return Result.success(appointment.get());
        } else {
            return Result.error(404, "预约记录不存在");
        }
    }

    /**
     * 分页查询预约
     */
    @GetMapping
    public Result<Page<Appointment>> getAppointmentList(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long elderlyId,
            @RequestParam(required = false) Long staffId,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String serviceType) {
        
        Pageable pageable = PageRequest.of(page, size);
        
        Appointment.AppointmentStatus statusEnum = null;
        if (status != null && !status.isEmpty()) {
            try {
                statusEnum = Appointment.AppointmentStatus.valueOf(status);
            } catch (IllegalArgumentException e) {
                return Result.error(400, "无效的预约状态");
            }
        }
        
        Page<Appointment> appointments = appointmentService.findAppointmentsWithFilters(
                elderlyId, staffId, statusEnum, serviceType, pageable);
        
        return Result.success(appointments);
    }

    /**
     * 获取老人的预约记录
     */
    @GetMapping("/elderly/{elderlyId}")
    public Result<Page<Appointment>> getAppointmentsByElderlyId(
            @PathVariable Long elderlyId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Pageable pageable = PageRequest.of(page, size);
        Page<Appointment> appointments = appointmentService.findByElderlyId(elderlyId, pageable);
        return Result.success(appointments);
    }

    /**
     * 获取护理人员的预约记录
     */
    @GetMapping("/staff/{staffId}")
    public Result<Page<Appointment>> getAppointmentsByStaffId(
            @PathVariable Long staffId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Pageable pageable = PageRequest.of(page, size);
        Page<Appointment> appointments = appointmentService.findByStaffId(staffId, pageable);
        return Result.success(appointments);
    }

    /**
     * 确认预约
     */
    @PutMapping("/{id}/confirm")
    public Result<Appointment> confirmAppointment(@PathVariable Long id) {
        try {
            Appointment appointment = appointmentService.confirmAppointment(id);
            return Result.success(appointment);
        } catch (RuntimeException e) {
            return Result.error(400, e.getMessage());
        }
    }

    /**
     * 开始预约服务
     */
    @PutMapping("/{id}/start")
    public Result<Appointment> startAppointment(@PathVariable Long id) {
        try {
            Appointment appointment = appointmentService.startAppointment(id);
            return Result.success(appointment);
        } catch (RuntimeException e) {
            return Result.error(400, e.getMessage());
        }
    }

    /**
     * 完成预约
     */
    @PutMapping("/{id}/complete")
    public Result<Appointment> completeAppointment(@PathVariable Long id) {
        try {
            Appointment appointment = appointmentService.completeAppointment(id);
            return Result.success(appointment);
        } catch (RuntimeException e) {
            return Result.error(400, e.getMessage());
        }
    }

    /**
     * 取消预约
     */
    @PutMapping("/{id}/cancel")
    public Result<Appointment> cancelAppointment(@PathVariable Long id, 
                                               @RequestParam String reason) {
        try {
            Appointment appointment = appointmentService.cancelAppointment(id, reason);
            return Result.success(appointment);
        } catch (RuntimeException e) {
            return Result.error(400, e.getMessage());
        }
    }

    /**
     * 获取预约统计信息
     */
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getAppointmentStatistics() {
        Map<String, Object> statistics = appointmentService.getAppointmentStatistics();
        return Result.success(statistics);
    }

    /**
     * 获取即将到来的预约
     */
    @GetMapping("/upcoming")
    public Result<List<Appointment>> getUpcomingAppointments() {
        List<Appointment> appointments = appointmentService.getUpcomingAppointments();
        return Result.success(appointments);
    }

    /**
     * 获取待确认的预约
     */
    @GetMapping("/pending")
    public Result<List<Appointment>> getPendingAppointments() {
        List<Appointment> appointments = appointmentService.getPendingAppointments();
        return Result.success(appointments);
    }
} 